package com.tang.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.tang.common.entity.user.User;
import com.tang.common.exception.RecruitExceptionEnum;
import com.tang.common.uniform.Constant;
import com.tang.common.uniform.Result;
import com.tang.common.utils.AfterMouthDate;
import com.tang.common.utils.JwtUtil;
import com.tang.common.utils.MD5Utils;
import com.tang.common.utils.UpLoad;
import com.tang.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication;
    }

    //用户列表
    @ApiOperation("用户列表")
    @GetMapping("/userList")
    public Result userList(Integer userType, String keywords, Integer currentPage, Integer pageSize,Integer expect) {
        PageInfo<User> list = null;
        if(expect==null){
             list = userService.list(userType, keywords, currentPage, pageSize);
        }else{
            list = userService.listExpectUser(currentPage, pageSize);
        }
        return Result.success(list);
    }

    //用户列表
    @ApiOperation("企业认证用户列表")
    @GetMapping("/authUserList")
    public Result authUserList(String keywords, Integer currentPage, Integer pageSize, Integer hasAuth) {
        PageInfo<User> list = userService.listAuthUser(keywords, currentPage, pageSize, hasAuth);
        return Result.success(list);
    }

    //用户列表
    @ApiOperation("用户详情")
    @GetMapping("/userDetail")
    public Result userDetail(String userName) {
        User user = userService.selectByUserName(userName);
        return Result.success(user);
    }

    //删除用户
    @ApiOperation("删除用户")
    @DeleteMapping("/delUser")
    public Result delUser(int userId) {
        int result = userService.deleteByUserId(userId);
        if (result != 0) {
            return Result.success("删除成功");
        } else {
            return Result.error(RecruitExceptionEnum.DELETE_FAILED);
        }
    }

    //启用禁用用户
    @ApiOperation("启用禁用用户")
    @PutMapping("/enableDisableUser")
    public Result enableDisableUser(int userId) {
        int result = userService.enableDisableByUserId(userId);
        if (result != 0) {
            return Result.success("操作成功");
        } else {
            return Result.error(RecruitExceptionEnum.HANDLE_FAILED);
        }
    }

    @ApiOperation("认证企业用户")
    @RequestMapping("/auditCompanyUser")
    public Result auditCompany(Integer userId, String res) {
        String result = userService.auditCompanyUser(userId, res);
        if("company-noAudit".equals(result)){
            return  Result.error(RecruitExceptionEnum.COMPANY_AUDIT);
        }
        if (result != null) {
            return Result.success(result);
        } else {
            return Result.error(RecruitExceptionEnum.AUDIT_FAILED);
        }
    }
    @RequestMapping("/companyUser")
    public Result companyUser(String companyName) {
        if (companyName != null) {
            List<User> list = userService.selectByCompanyName(companyName);
            if (list != null) {
                return Result.success(list);
            }

        }
        return null;
    }

    //登录
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(String userName, String password, String captcha, HttpSession session) {
        User user = userService.find(userName, MD5Utils.getMD5Str(password));
        if (user == null) {
            return Result.error(RecruitExceptionEnum.LOGIN_FAILED);
        }
        if (user.getState() == 0) {
            return Result.error(RecruitExceptionEnum.USER_DISABLE);
        }
        if (captcha != null) {
            if (!captcha.equals(session.getAttribute(Constant.CAPTCHA))) {
                return Result.error(RecruitExceptionEnum.CAPTCHA_ERROR);
            }
        }
        String role = null;
        if (user.getUserType() == 0) {
            role = "user";
        } else if (user.getUserType() == 1) {
            role = "companyUser";
        }
        String token = JwtUtil.generateToken(userName, MD5Utils.getMD5Str(password), role);
        System.out.println(token);
        List list = new ArrayList();
        list.add(user);
        list.add(token);
        return Result.success(list);
    }


    //登录
    @ApiOperation("用户登录")
    @PostMapping("/phoneLogin")
    public Result phoneLogin(String tel, String captcha, HttpSession session) {
        if (captcha == null || !session.getAttribute("phoneCaptcha").equals(captcha)) {
            return Result.error(RecruitExceptionEnum.CAPTCHA_ERROR);
        }
        User user = userService.selectByTel(tel);
        if (user == null) {
            return Result.error(RecruitExceptionEnum.LOGIN_FAILED);
        }
        if (user.getState() == 0) {
            return Result.error(RecruitExceptionEnum.USER_DISABLE);
        }
        String role = null;
        if (user.getUserType() == 0) {
            role = "user";
        } else if (user.getUserType() == 1) {
            role = "companyUser";
        }
        String token = JwtUtil.generateToken(user.getUserName(), user.getPassword(), role);
        System.out.println(token);
        List list = new ArrayList();
        list.add(user);
        list.add(token);
        return Result.success(list);
    }


    //用户退出登录
    @ApiOperation("管理员退出登录")
    @RequestMapping("/logout")
    public Result logout(HttpSession session) {
        session.invalidate();
        return Result.success("退出成功");
    }

    //账户注销
    @ApiOperation("账户注销")
    @DeleteMapping("/logoutUser")
    public Result logoutUser(String password, HttpServletRequest request, HttpSession session) {
        String token = request.getHeader("TOKEN");
        String username = JwtUtil.get(token, "username");
        String pwd = JwtUtil.get(token, "password");
        session.invalidate();
        if (pwd.equals(MD5Utils.getMD5Str(password))) {
            int result = userService.deleteByUserName(username);
            if (result != 0) {
                return Result.success("注销成功");
            }
        }
        return Result.error(RecruitExceptionEnum.LOGOUT_FAILED);
    }

    //修改密码
    @ApiOperation("修改密码")
    @PutMapping("/pwdChange")
    public Result pwdChange(String password, String newPassword, HttpServletRequest request) {
        String token = request.getHeader("TOKEN");
        String username = JwtUtil.get(token, "username");
        User user = userService.selectByUserName(username);
        if (!user.getPassword().equals(MD5Utils.getMD5Str(password))) {
            return Result.error(RecruitExceptionEnum.OLDPASSWORD_ERROR);
        }
        user.setPassword(MD5Utils.getMD5Str(newPassword));
        user.setUpdateTime(new Date());
        int result = userService.updateUser(user);
        if (result != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error(RecruitExceptionEnum.UPDATE_FAILED);
        }
    }

    //修改密码
    @ApiOperation("忘记密码")
    @PutMapping("/forgetPwd")
    public Result forgetPwd(String userName, String newPassword, String tel, String captcha, HttpSession session) {
        User user = userService.selectByUserName(userName);
        if (user == null) {
            return Result.error(RecruitExceptionEnum.USER_NOT_EXIST);
        }
        if (captcha == null || !session.getAttribute("phoneCaptcha").equals(captcha)) {
            return Result.error(RecruitExceptionEnum.CAPTCHA_ERROR);
        }
        if (!tel.equals(user.getTel())) {
            return Result.error(RecruitExceptionEnum.TEL_FAILED);
        }
        user.setPassword(MD5Utils.getMD5Str(newPassword));
        user.setUpdateTime(new Date());
        int result = userService.updateUser(user);
        if (result != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error(RecruitExceptionEnum.UPDATE_FAILED);
        }
    }

    //获取个人信息
    @ApiOperation("获取个人信息")
    @GetMapping("/personInfo")
    public Result personInfo(String userName) {
        User user = userService.selectByUserName(userName);
        if (user.getVipDueTime() != null) {
            if (user.getVipDueTime().before(new Date())) {
                user.setVip(0);
                userService.updateUser(user);
            }
        }
        return Result.success(user);
    }

    //获取个人信息
    @ApiOperation("获取个人信息")
    @GetMapping("/noPassUser")
    public Result noPassAllUser(String companyName) {
        Boolean b = userService.noPassUser(companyName);
       if(b){
           return Result.success("该公司认证用户已全部不通过");
       }
       return null;
    }
    //注册
    @ApiOperation("注册")
    @PutMapping("/register")
    public Result register(String userName, String password, String tel, String captcha, HttpSession session) {
        if (captcha == null || !session.getAttribute("phoneCaptcha").equals(captcha)) {
            return Result.error(RecruitExceptionEnum.CAPTCHA_ERROR);
        }
        User user1 = userService.selectByUserName(userName);
        if (user1 != null) {
            return Result.error(RecruitExceptionEnum.USER_HAS_EXIST);
        }
        User user = userService.selectByTel(tel);
        if (user != null) {
            return Result.error(RecruitExceptionEnum.TEL_HAS_USE);
        }
        User user2 = new User();
        user2.setUserName(userName);
        user2.setTel(tel);
        user2.setPassword(MD5Utils.getMD5Str(password));
        int i = userService.addUser(user2);
        if (i != 0) {
            return Result.success("注册成功");
        }
        return Result.error(RecruitExceptionEnum.HANDLE_FAILED);
    }

    //注册
    @ApiOperation("认证")
    @RequestMapping("/register/upload")
    public Result register(
            @RequestParam("position") String position,
            @RequestParam("companyId") Integer companyId,
            @RequestParam("companyName") String companyName,
            @RequestParam("userEmail") String userEmail,
            @RequestParam("realName") String realName,
            @RequestParam("file") List<MultipartFile> file,
            HttpServletRequest request
    ) {
        String token = request.getHeader("TOKEN");
        String username = JwtUtil.get(token, "username");
        User user = userService.selectByUserName(username);
        if (user != null) {
            user.setPosition(position);
            if (!file.isEmpty()) {
                List<String> files = UpLoad.upload(file);
                if (!files.isEmpty()) {
                    user.setAuthUrl(files.get(0));
                }
            }
            user.setHasAuth(0);
            user.setRealName(realName);
            user.setEmail(userEmail);
            user.setCompanyId(companyId);
            user.setCompanyName(companyName);
            int i = userService.updateUser(user);
            if (i != 0) {
                return Result.success("提交成功");
            }
        }
        return Result.error(RecruitExceptionEnum.HANDLE_FAILED);
    }

    //修改个人信息
    @ApiOperation("修改个人信息")
    @SneakyThrows
    @PostMapping("/updatePersonInfo")
    public Result updatePersonInfo(
            String graduate,
            String edu,
            String expect,
            String qq,

            String userName,
            String pickName,
            String sex,
            Integer age,
            String tel,
            String email,
            String liveCity,
            String position,
            String introduce,
            String photoUrl
    ) {
        User user = userService.selectByTel(tel);
        if (user != null && !user.getUserName().equals(userName)) {
            return Result.error(RecruitExceptionEnum.TEL_HAS_USE);
        }
        int result = 0;
        if (userName != null) {
            User user2 = userService.selectByUserName(userName);
            user2.setQq(qq);
            user2.setGraduate(graduate);
            user2.setExpect(expect);
            user2.setEdu(edu);
            user2.setPickName(pickName);
            user2.setSex(sex);
            user2.setAge(age);
            user2.setTel(tel);
            user2.setEmail(email);
            user2.setLiveCity(liveCity);
            user2.setPosition(position);
            user2.setIntroduce(introduce);
            user2.setPhotoUrl(photoUrl);
            System.err.println(user2);
            result = userService.updateUser(user2);
        }
        if (result != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error(RecruitExceptionEnum.UPDATE_FAILED);
        }
    }


    @RequestMapping("/createVip")
    public Result createVip(Integer userId) {
        if (userId != null) {
            User user = userService.selectById(userId);
            if (user != null) {
                if (user.getVipDueTime() == null) {
                    user.setVip(1);
                    user.setVipCreateTime(new Date());
                    user.setVipDueTime(AfterMouthDate.getMonthDate(new Date(), 1));
                    int i = userService.updateUser(user);
                    if (i != 0) {
                        return Result.success(user);
                    }
                }
                if (user.getVipDueTime().before(new Date())) {
                    user.setVip(1);
                    user.setVipCreateTime(new Date());
                    user.setVipDueTime(AfterMouthDate.getMonthDate(new Date(), 1));
                    int i = userService.updateUser(user);
                    if (i != 0) {
                        return Result.success(user);
                    }
                }
                if (user.getVipDueTime().after(new Date())) {
                    user.setVip(1);
                    user.setVipCreateTime(new Date());
                    user.setVipDueTime(AfterMouthDate.getMonthDate(user.getVipDueTime(), 1));
                    int i = userService.updateUser(user);
                    if (i != 0) {
                        return Result.success(user);
                    }
                }
            }

        }
        return Result.error(RecruitExceptionEnum.CREATE_FAILED);
    }
}
